import { Button, Input, Select } from 'antd'
import { isEmpty } from 'lodash'
import React, { useRef, useState } from 'react'
import { connect } from 'react-redux'
import { useHistory } from 'react-router-dom'
import CountryCodeSelect from '../../components/country-code-select/CountryCodeSelect'
import MobileInput from '../../components/mobile-input/MobileInput'
import useCaptcha, { ISMCaptchaInstance } from '../../hooks/useCaptcha'
import { E_ROUTE_PATH } from '../../router/route-path'
import { serviceContext } from '../../service/context'
import { E_ERROR_CODE } from '../../service/typing/enum/error-code'
import { E_EDUCATION_MODE, E_EDUCATION_ROLE } from '../../service/typing/enum/service-enum'
import { IRegisterParam } from '../../service/typing/service/IAuthService'
import { ISendMobileVerifyCodeParam } from '../../service/typing/service/IClientService'
import { IAuthAction, setIsLoggedIn, setToken } from '../../store/modules/auth'
import { isValidMobile } from '../../utils/validation'
import './Register.less'

type IDispatchProps = Partial<IAuthAction>

type IRegisterProps = IDispatchProps

function Register(props: IRegisterProps) {
  const SMCaptchaInstance = useRef<ISMCaptchaInstance>()
  let captcha = ''
  const mobileRef = useRef('')
  const history = useHistory()

  const [countryCode, setCountryCode] = useState('86')
  const [errorMsg, setErrorMsg] = useState('')
  const [name, setName] = useState('')
  const [mobile, setMobile] = useState('')
  const [verifyCode, setVerifyCode] = useState('')
  const [educationMode, setEducationMode] = useState('')

  function checkInput() {
    if (isEmpty(name)) {
      setErrorMsg('请输入姓名')
      return false
    }

    if (isEmpty(mobile)) {
      setErrorMsg('请输入手机号码')
      return false
    }

    if (!isValidMobile(mobile)) {
      setErrorMsg('请输入正确的手机号码')
      return false
    }
    if (isEmpty(verifyCode)) {
      setErrorMsg('请输入短信验证码')
      return false
    }

    if (isEmpty(educationMode)) {
      setErrorMsg('请选择教育模式')
      return false
    }

    return true
  }

  function formatEducationMode() {
    let mode: E_EDUCATION_MODE
    switch (educationMode) {
      case '1':
        mode = E_EDUCATION_MODE.K9
        break
      case '2':
        mode = E_EDUCATION_MODE.K12
        break
      case '3':
        mode = E_EDUCATION_MODE.AUDIT
        break
      case '4':
        mode = E_EDUCATION_MODE.QUALITY
        break
      default:
        mode = E_EDUCATION_MODE.K9
        break
    }

    return mode
  }

  async function register() {
    const param: IRegisterParam = {
      name,
      countryCode: countryCode,
      mobile,
      verifyCode,
      educationMode: formatEducationMode(),
      educationRole: E_EDUCATION_ROLE.TEACHER,
      registerType: 'MOBILE_VERIFYCODE_REGISTER',
      source: 'WEB',
      terminalType: 'WEB',
      productId: 60000,
      accountType: 1
    }

    const result = await serviceContext.get().auth.register(param)
    if (result.errorCode === E_ERROR_CODE.SUCCESS) {
      props.setIsLoggedIn && props.setIsLoggedIn(true)
      const token = result.data?.token || ''
      props.setToken && props.setToken(token)
      const userId = result.data?.umsUserId || 0
      props.setUserId && props.setUserId(userId)

      history.replace(E_ROUTE_PATH.COURSE_LIST)
    } else {
      if (result.errorCode && result.errorCode < 1000) {
        setErrorMsg('注册失败，请稍后重试')
      } else {
        setErrorMsg(result.errorMsg || '')
      }
    }
  }

  function onClickRegisterBtn() {
    setErrorMsg('')
    const isPassed = checkInput()
    if (!isPassed) {
      return
    }

    register()
  }

  function verifyTextCode() {
    SMCaptchaInstance.current?.reset()
    SMCaptchaInstance.current?.verify()
  }

  async function sendVerifyCode() {
    const param: ISendMobileVerifyCodeParam = {
      countryCode,
      mobile: mobileRef.current,
      captchaValidate: captcha
    }
    const result = await serviceContext.get().client.sendMobileVerifyCode(param)
    if (result.errorCode === E_ERROR_CODE.SUCCESS) {
      const data = result.data
      if (!isEmpty(data?.verifyCode)) {
        setVerifyCode(data!!.verifyCode)
      }
    }
  }

  function onEducationModeSelected(value: string) {
    setEducationMode(value)
  }

  function onMobileChanged(value: string) {
    setMobile(value)
    mobileRef.current = value
  }

  useCaptcha({
    onReady: instance => {
      SMCaptchaInstance.current = instance
    },
    onSuccess: data => {
      if (data.pass) {
        captcha = data.rid

        sendVerifyCode()
      }
    },
    onError: () => {}
  })

  return (
    <div className="register">
      <div className="form-container">
        <div className="form">
          <div className="title">申请免费试用</div>
          <div className="sub-title">成功后，即可获得60分钟免费体验</div>
          <div className={!!errorMsg ? 'error-msg msg-tips' : 'error-msg msg-tips hide'} title={errorMsg}>
            {errorMsg}
          </div>
          <Input className="input-name input" placeholder="姓名" bordered={false} allowClear onChange={e => setName(e.target.value)} />
          <div className="h-divider" />

          <div className="mobile-input-node">
            <CountryCodeSelect defaultValue={countryCode} bordered={false} className="country-code" onChange={value => setCountryCode(value)} />
            <div className="v-divider" />
            <MobileInput
              className="input-mobile input"
              placeholder="手机号"
              bordered={false}
              allowClear
              value={mobile}
              onValueChange={onMobileChanged}
            />
          </div>
          <div className="h-divider" />

          <div className="input-verify-code-node">
            <Input
              className="input-verify-code input"
              value={verifyCode}
              placeholder="短信验证码"
              bordered={false}
              allowClear
              onChange={e => setVerifyCode(e.target.value)}
            />
            <Button disabled={!isValidMobile(mobile)} className="btn-send-verify-code" type="link" onClick={() => verifyTextCode()}>
              获取验证码
            </Button>
          </div>

          <div className="h-divider" />

          <Select className="select-education-mode" bordered={false} placeholder="选择教育模式" onChange={onEducationModeSelected}>
            <Select.Option value="1">K9</Select.Option>
            <Select.Option value="2">K0-K12</Select.Option>
            <Select.Option value="3">成人教育</Select.Option>
            <Select.Option value="4">素质教育</Select.Option>
          </Select>
          <div className="h-divider" />

          <div className={educationMode === '1' ? 'k9-tips msg-tips' : 'k9-tips msg-tips hide'}>
            依国家政策要求，仅允许周一至周五且不得超过21:00教学
          </div>

          <Button className="btn-register" type="primary" shape="round" onClick={onClickRegisterBtn}>
            立即试用
          </Button>
        </div>
      </div>
    </div>
  )
}

const mapAction = {
  setIsLoggedIn,
  setToken
}

export default connect(null, mapAction)(Register)
